<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible">
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-print>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="true"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="handelPrint"
          ></PopoverPrint>
        </template>
      </page-filter>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        :checkBox="false"
        :tabIndex="true"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-evaluateItemScore="scope">
          <span>{{
            scope.row[
              `evaluateItemScore_${scope.childIndex}_${scope.index - 7}`
            ]
          }}</span>
        </template>
      </table-container>
    </div>
    <modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      @returnModify="getList"
    />

    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="evaluationRecord">
import PageFilter from '@/components/PageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import { doPrint } from '@/utils/exportUtil.js'
import {
  getEnabledEvaluateTemplate,
  excelListEvaluateRecord,
  printEvaluateRecord,
  getEvaluateTemplateAll,
  getEvaluateRecordPage,
  deleteEvaluateRecord,
  getEvaluateTemplateById,
} from '@/api/evaluate'
import { getSupplierAll, getDeptAll } from '@/api/core'
import { getRrgUserAll, fatchTemplateByCode } from '@/api/base.js'
import Modify from './modify'
import PageDialog from '@/components/PageDialog/index'
import { selectByCodeAndDept } from '@/api/report.js'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

// 过滤相关配置
const filterInfo = reactive({
  query: {
    sort: 'id desc',
    deptAuth: 'deptId',
    supplierAuth: 'supplierId',
    evaluateTemplateId: '',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('evaluationRecord:add'),
    },

    {
      label: '评价体系',
      value: 'evaluateTemplateId',
      type: 'slip-select',
      api: getEvaluateTemplateAll,
      query: { sort: 'create_time desc' },
      keyField: 'templateName',
      valueField: 'id',
      clearable: false,
      event: evaluateTemplateSearch,
    },
    {
      label: '供应商',
      value: 'supplierIdMult',
      type: 'slip-select',
      api: getSupplierAll,
      query: { supplierAuth: 'supplierId', sort: 'create_time desc' },
      clearable: true,
      multiple: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      event: search,
    },
    {
      type: 'date',
      clearable: true,
      label: '年度',
      value: 'evaluateYear',
      dateType: 'year',
      valueFormat: 'YYYY',
      event: search,
    },
    {
      type: 'select-model',
      code: 'period_type',
      clearable: true,
      label: '期间类型',
      value: 'periodType',
      event: search,
    },
    {
      type: 'select-model',
      code: 'half_year',
      clearable: true,
      label: '评价期间',
      value: 'periodValue',
      event: search,
    },
    {
      type: 'slip-select',
      label: '评价人',
      value: 'updateUser',
      api: getRrgUserAll,
      event: search,
    },
    {
      type: 'slip-select',
      label: '评价部门',
      value: 'deptIdMult',
      api: getDeptAll,
      query: { deptAuth: 'id', status: 1 },
      multiple: true,
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
    // {
    //   type: 'button',
    //   label: '打印',
    //   event: print,
    //   show: proxy.$permission('evaluationRecord:print'),
    // },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('evaluationRecord:print'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('evaluationRecord:export'),
    },
  ],
})
// 表格相关
let classifyFieldList = []
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: null,
  data: [],
  selections: [],
  fieldList: [
    { label: '评价人', value: 'updateUserName' },
    { label: '评价部门', value: 'deptName' },
    { label: '年度', value: 'evaluateYear' },
    { label: '期间类型', value: 'periodTypeDict' },
    { label: '评价期间', value: 'periodValueDict' },
    { label: '供应商', value: 'supplierName' },
    { label: '评价体系', value: 'evaluateTemplateName' },
    { label: '合计', value: 'totalScore' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '90',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('evaluationRecord:update'),
      },
      {
        label: '删除',
        event: del,
        show: proxy.$permission('evaluationRecord:remove'),
      },
    ],
  },
})
const modifyInfo = reactive({
  visible: false,
  title: '',
  orderId: '',
})

let page = reactive({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const dialogInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})

watch(
  () => filterInfo.query.periodType,
  (val) => {
    if (Number(val) === 1) {
      //期间类型取值为年度时，输入框
      filterInfo.list.forEach((item) => {
        if (item.value === 'periodValue') {
          item.type = 'input'
        }
      })
    } else if (Number(val) === 2) {
      //期间类型为半年度时，取值为上半年、下半年，
      filterInfo.list.forEach((item) => {
        if (item.value === 'periodValue') {
          item.code = 'half_year'
          item.type = 'select-model'
        }
      })
    } else if (Number(val) === 3) {
      //期间类型为季度时，取值为1~4季度，
      filterInfo.list.forEach((item) => {
        if (item.value === 'periodValue') {
          item.code = 'quarter'
          item.type = 'select-model'
        }
      })
    } else if (Number(val) === 4) {
      //期间类型为月度时，取值为1~12月份，
      filterInfo.list.forEach((item) => {
        if (item.value === 'periodValue') {
          item.code = 'month'
          item.type = 'select-model'
        }
      })
    }
  },
  {
    deep: true,
  }
)

onMounted(() => {
  getTemplate()
})

function returnModify() {
  if (modifyInfo.tableRow && modifyInfo.tableRow.id) {
    getList()
  } else {
    search()
  }
}
// 获取列表
function getList() {
  tableInfo.api = getEvaluateRecordPage
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  // tableInfo.refresh = Math.random();
  getList()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      tableInfo.data = data

      tableInfo.data.forEach((i) => {
        i.details.forEach((row) => {
          classifyFieldList.forEach((item, index) => {
            item.children.forEach((el, elIndex) => {
              if (
                row.evaluateItemName === el.evaluateItemName &&
                row.evaluateClassifyName === el.classifyName
              ) {
                i[`evaluateItemScore_${elIndex}_${index}`] =
                  row.evaluateItemScore
              }
            })
          })
        })
      })
      break
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
//创建
function create() {
  modifyInfo.title = '新增评价记录'
  modifyInfo.orderId = ''
  modifyInfo.visible = true
}
//更新
function update(row) {
  modifyInfo.title = '修改评价记录'
  modifyInfo.orderId = row.id
  modifyInfo.visible = true
}

function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
//删除
function del(row) {
  const ids = _getIds(row)
  deleteEvaluateRecord(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.selections.length > 0) {
      ids = tableInfo.selections.map((row) => row.id)
    }
  }
  return ids
}
function getTemplate() {
  getEnabledEvaluateTemplate().then((res) => {
    if (res && res.success) {
      filterInfo.query.evaluateTemplateId = res.data.id
      getTableField(res.data.id)
    }
  })
}
function evaluateTemplateSearch(val) {
  getTableField(val)
}
function getTableField(id) {
  getEvaluateTemplateById(id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data.classifyDetails
      classifyFieldList = data.map((item) => {
        let obj = {
          label: `${item.classifyName}(${item.classifyScore})分`,
          type: 'multiHeader',
          children: [],
        }
        obj.children = item.itemDetails.map((el) => {
          return {
            label: `${el.itemName}(${el.itemScore})分`,
            value: `evaluateItemScore`,
            type: 'slot',
            classifyName: item.classifyName,
            evaluateItemName: el.itemName,
            itemScore: el.itemScore,
            width: '180px',
          }
        })
        return obj
      })
      let arr1 = [
        { label: '评价人', value: 'updateUserName' },
        { label: '评价部门', value: 'deptName' },
        { label: '年度', value: 'evaluateYear' },
        { label: '期间类型', value: 'periodTypeDict' },
        { label: '评价期间', value: 'periodValueDict' },
        { label: '供应商', value: 'supplierName' },
        { label: '评价体系', value: 'evaluateTemplateName' },
      ]
      let arr2 = [
        {
          label: '合计',
          value: 'totalScore',
        },
        {
          label: '备注',
          value: 'remark',
        },
      ]
      console.log(arr1.concat(classifyFieldList, arr2))
      tableInfo.fieldList = arr1.concat(classifyFieldList, arr2)
    }
    getList()
  })
}
async function handelPrint() {
  dialogInfo.visible = true
  dialogInfo.type = 'print'
  dialogInfo.msg = '请选择当数据打印范围'
  dialogInfo.btList[1].label = '打印'
  dialogInfo.flag = true
}
function exportExcel() {
  dialogInfo.visible = true
  dialogInfo.type = 'excel'
  dialogInfo.msg = '请选择数据导出范围'
  dialogInfo.btList[1].label = '导出'
  dialogInfo.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.query,
    ...page,
    page: dialogInfo.flag,
  }
  excelListEvaluateRecord(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const popoverVisible = ref(false)
const templateArr = ref([])
function printList() {
  selectByCodeAndDept({
    tempCode: 'evaluationRecord:print',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            evaluateTemplateId:filterInfo.query.evaluateTemplateId,
            supplierIdMult:filterInfo.query.supplierIdMult,
            evaluateYear:filterInfo.query.evaluateYear,
            periodType:filterInfo.query.periodType,
            updateUser:filterInfo.query.updateUser,
            deptIdMult:filterInfo.query.deptIdMult,
            periodValue:filterInfo.query.periodValue,
            curPage:(page.curPage-1)*page.pageSize,
            pageSize:page.pageSize,
            page: dialogInfo.flag,
          },
          callback: printCallback,
        })
      }
    }
    // if (res && res.success) {
    //   let temp = proxy.$fn.getPrintTemp(res.data[0])
    //   getPrintData(temp, dialogInfo.flag)
    // }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      evaluateTemplateId:filterInfo.query.evaluateTemplateId,
      supplierIdMult:filterInfo.query.supplierIdMult,
      evaluateYear:filterInfo.query.evaluateYear,
      periodType:filterInfo.query.periodType,
      updateUser:filterInfo.query.updateUser,
      deptIdMult:filterInfo.query.deptIdMult,
      periodValue:filterInfo.query.periodValue,
      curPage:(page.curPage-1)*page.pageSize,
      pageSize:page.pageSize,
      page: dialogInfo.flag,
    },
    callback: printCallback,
    data: {
      customParam: JSON.stringify({
        ...filterInfo.query,
        ...page,
        page: dialogInfo.flag,
      }),
    },
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
  } catch (error) {}
}
function checkConfirm() {
  if (dialogInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.type === 'print') {
    printList()
  }
  dialogInfo.visible = false
  dialogInfo.msg = ''
}
function pageInfo(obj) {
  page = obj
}
function getPrintData(temp, flag) {
  let query = {
    queryParams: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: flag,
  }
  printEvaluateRecord(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function handleClose() {
  dialogInfo.visible = false
}
</script>

<style scoped></style>
